# -*- coding: utf-8 -*-
import requests
import re
import xlwt
import xlrd
# import pickle
from bs4 import BeautifulSoup
import json
from Performance import models
from threading import Thread


# python2 和 python3的兼容代码
try:
    import cookielib

    print(f"user cookielib in python2.")
except:
    import http.cookiejar as cookielib

    print(f"user cookielib in python3.")


def read_excel():
    ExcelFile = xlrd.open_workbook('test2.xls')
    sheet = ExcelFile.sheet_by_name('test')
    cols = sheet.col_values(2)  # 第二列内容

    fileList = []
    tranList = []
    language = ['zh', 'hk', 'en', 'ja', 'es', 'pt', 'br', 'fr', 'de', 'ko']
    languageRow = 4
    for lang in language:
        tranList.append(sheet.col_values(languageRow))
        f = open(lang + '.txt', 'wb')
        f.truncate()
        fileList.append(f)
        languageRow += 1

    row = 0
    for name in cols:
        type = sheet.cell_type(row, 1)
        if (type == 1 and name != ""):
            languageIndex = 0
            for lang in language:
                txt = tranList[languageIndex][row]
                value = txt.replace('%@', '%s')
                text = '<' + 'string name=' + '\"' + name.strip() + '\"' + '>' + value.strip() + '</string>' + '\n'
                fileList[languageIndex].write((text.encode("utf-8")))
                languageIndex += 1
        row += 1

    for fileHandle in fileList:
        fileHandle.close()


workbook = xlwt.Workbook()
sheet1 = workbook.add_sheet('test', cell_overwrite_ok=True)

# session代表某一次连接
mafengwoSession = requests.session()
# 因为原始的session.cookies 没有save()方法，所以需要用到cookielib中的方法LWPCookieJar，这个类实例化的cookie对象，就可以直接调用save方法。

userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"
header = {
    "Referer": "http://wiki.orvibo.com:8190/login.action?os_destination=%2Fpages%2Fviewpage.action%3FpageId%3D43352241&permissionViolation=true",
    'User-Agent': userAgent,
}


def writeFile(fileName, data, extension='txt'):
    f = open(fileName + '.' + extension, 'wb')
    f.truncate()
    # f.write((data.encode("utf-8")))
    f.write((''.join(data).encode("utf-8")))
    f.close()

def hmSubstr(source,begin,end):
    if source.find(begin):
        startIndex = source.find(begin)
        if source.find(end) > startIndex:
            endIndex = source.find(end) + len(end)
            result = source[startIndex:endIndex]
            return result
    return ''



def loginOrviboWiki(account, password):
    print("开始模拟登陆Confluence")
    # postUrl = "http://wiki.orvibo.com:8190/dologin.action"
    postUrl = "http://wiki.orvibo.com:8189/login.jsp"
    postData = {
        "os_username": account,
        "os_password": password,
        "login": "登录",
        "os_destination": "/pages/viewpage.action?pageId=47251585"
    }
    # 使用session直接post请求
    responseRes = mafengwoSession.post(postUrl, data=postData, headers=header)

    print("post登录请求:\n")
    print(responseRes)

    # url = "http://wiki.orvibo.com:8189/issues/?filter=14519"
    # url = "http://wiki.orvibo.com:8190/pages/viewpage.action?pageId=47251585"

    statistics()
    # writeFile('4444', html, 'html')

def async(f):
    def wrapper(*args, **kwargs):
        thr = Thread(target = f, args = args, kwargs = kwargs)
        thr.start()
    return wrapper

@async
def statistics():
    print('开始statistics')

    # list = parse_v3_4()
    # list = parse_v3_3()

    # list += parse_v3_4()
    # list += parse_v3_5()
    # list += parse_v3_6()
    # list += parse_v3_7()

    list = parse_v3_8()
    list += parse_v3_9()
    list += parse_v4_0()

    saveBugToDb(list)

    print('执行了statistics')


def saveBugToDb(list):

    # f = open('5555.txt', 'w')
    for dic in list:
        bug = models.Bug()
        bug.bugNo = dic['bugNo']
        bug.priority = dic['priority']
        bug.score = dic['score']
        bug.title = dic['title']
        bug.label = dic['label']
        bug.label1 = dic['label1']
        bug.label2 = dic['label2']
        bug.person = dic['person']
        bug.sprint = dic['sprint']
        bug.version = dic['version']
        bug.save()
    #     f.write(json.dumps(dic, ensure_ascii=False))
    #     f.write('\n')
    # f.close()


def parse_v3_3():
    version = '3.3'
    url = "http://wiki.orvibo.com:8189/issues/?filter=14519&jql=project%20%3D%20HM%20AND%20issuetype%20%3D%20%E7%BC%BA%E9%99%B7%20AND%20Sprint%20in%20(171%2C%20152%2C%20154%2C%20147%2C%20151%2C%20153%2C%20162%2C%20178%2C%20170%2C%20172%2C%20180%2C%20179%2C%20163%2C%20150%2C%20161%2C%20148%2C%20164)%20AND%20%E7%B3%BB%E7%BB%9F%E5%B9%B3%E5%8F%B0%20%3D%20iOS%20ORDER%20BY%20priority%20DESC%2C%20labels%20DESC%2C%20key%20DESC%2C%20summary%20DESC%2C%20issuetype%20DESC"
    url2 = url + '&startIndex=100'
    url3 = url + '&startIndex=200'
    url4 = url + '&startIndex=300'
    url5 = url + '&startIndex=400'
    list = parse(url,version) + parse(url2,version)+ parse(url3,version)+ parse(url4,version) + parse(url5,version)

    print('{}版本Bug总数为：{}'.format(version, len(list)))
    return list
    # bugNo = models.IntegerField(primary_key=True, unique=True)
    # priority = models.IntegerField()
    # title = models.CharField(max_length=512)
    # label = models.CharField(max_length=128)
    # label1 = models.CharField(max_length=128)
    # label2 = models.CharField(max_length=128)
    # person = models.CharField(max_length=128)
    # sprint = models.CharField(max_length=256)
    # version = models.CharField(max_length=128)

    # f = open('5555.txt', 'wb')
    # print('3.3 bug 总数为：',len(list))


def parse_v3_4():

    version = '3.4'
    url = "http://wiki.orvibo.com:8189/issues/?filter=14517"
    url2 = url + '&startIndex=100'
    list = parse(url, version) + parse(url2,version)
    print('{}版本Bug总数为：{}'.format(version, len(list)))
    return list

def parse_v3_5():
    version = '3.5'
    url = "http://wiki.orvibo.com:8189/issues/?filter=14521"
    url2 = url + '&startIndex=100'
    url3 = url + '&startIndex=200'
    list = parse(url, version) + parse(url2, version) + parse(url3, version)
    print('{}版本Bug总数为：{}'.format(version, len(list)))
    return list


def parse_v3_6():
    version = '3.6'
    url = "http://wiki.orvibo.com:8189/issues/?filter=14523"
    url2 = url + '&startIndex=100'
    url3 = url + '&startIndex=200'
    list = parse(url, version) + parse(url2, version) + parse(url3, version)
    print('{}版本Bug总数为：{}'.format(version, len(list)))
    return list

def parse_v3_7():
    version = '3.7'
    url = "http://wiki.orvibo.com:8189/issues/?filter=14524"
    list = parse(url, version)
    print('{}版本Bug总数为：{}'.format(version, len(list)))
    return list

def parse_v3_8():
    version = '3.8'
    url = "http://wiki.orvibo.com:8189/issues/?filter=15203"
    url2 = url + '&startIndex=100'
    url3 = url + '&startIndex=200'
    list = parse(url,version) + parse(url2,version)+ parse(url3,version)

    print('{}版本Bug总数为：{}'.format(version, len(list)))
    return list


def parse_v3_9():

    version = '3.9'
    url = "http://wiki.orvibo.com:8189/issues/?filter=15204"
    url2 = url + '&startIndex=100'
    list = parse(url, version) + parse(url2,version)
    print('{}版本Bug总数为：{}'.format(version, len(list)))
    return list

def parse_v4_0():
    version = '3.5'
    url = "http://wiki.orvibo.com:8189/issues/?filter=15205"
    url2 = url + '&startIndex=100'
    url3 = url + '&startIndex=200'
    list = parse(url, version) + parse(url2, version) + parse(url3, version)
    print('{}版本Bug总数为：{}'.format(version, len(list)))
    return list


def parse(url,version):

    html = mafengwoSession.get(url, headers=header,allow_redirects=True).text
    soup = BeautifulSoup(html, 'html.parser')
    buglist = soup.find('tbody').children

    # for idx, li in enumerate(td.div.ul.contents):
    bugs = []
    for cols in buglist:
        # 找出其中一行
        if cols.name == 'tr':
            dic = {}
            for td in cols.contents:

                if td.name == 'td': # 找出其中一列
                    name = td['class'][0]
                    if name == "issuekey":  # 找出Bug编号
                        bugNo = td.a['title']
                        dic['bugNo'] = bugNo
                    elif name == "priority":  # 找出Bug等级
                        priority = td.img['alt']

                        if priority == '致命':
                            dic['priority'] = 1
                            dic['score'] = -20
                        elif priority == '严重':
                            dic['priority'] = 2
                            dic['score'] = -15
                        elif priority == '一般':
                            dic['priority'] = 3
                            dic['score'] = -10
                        else:
                            dic['priority'] = 4
                            dic['score'] = -5

                    elif name == "summary":  # 找出Bug标题
                        title = td.p.a.string
                        dic['title'] = title
                    elif name =="labels":  # 找出Bug标签
                        idx = 0
                        # for idx,li in enumerate(td.div.ul.contents):
                        dic['label'] = ''
                        dic['label1'] = ''
                        dic['label2'] = ''
                        if td.div.ul:
                            for li in td.div.ul.contents:
                                if li.name == 'li':
                                    label = li.a['title']
                                    if idx == 0:
                                        dic['label'] = label
                                    elif idx == 1:
                                        dic['label1'] = label
                                    else:
                                        dic['label2'] = label
                                    idx = idx + 1
                    elif name =="customfield_10200":  # 找出解决人
                        if td.contents:
                            person = td.span.a.string
                            dic['person'] = person
                        else:
                            dic['person'] = ''
                    elif name == "customfield_10001":  # 找出sprint
                        sprint = td.string
                        dic['sprint'] = sprint
            if dic['label'] == '替他人解决' or dic['label1'] == '替他人解决' or dic['label2'] == '替他人解决':
                if dic['priority'] == 1:
                    dic['score'] = 30
                elif dic['priority'] == 2:
                    dic['score'] = 15
                elif dic['priority'] == 3:
                    dic['score'] = 10
                else:
                    dic['score'] = 5

            dic['version'] = version
            bugs.append(dic)
    return bugs



def saveSheet():

    # s = colTxt
    # start = colTxt.find('title="')
    # end = colTxt.find('"></a>')
    # butNo = colTxt[start + 7:end]
    # print('====={} --> {}'.format(s, butNo))

    #     rowTxt = rowTxt.replace('％', '%')
    #     rowTxt = rowTxt.replace('<span>', '')
    #     rowTxt = rowTxt.replace('</span>', '')
    #     rowTxt = rowTxt.replace('<pre>', '')
    #     rowTxt = rowTxt.replace('</pre>', '')
    #     rowTxt = rowTxt.replace('\'', '\\\'')
    #
    #     if rowTxt != "":
    #         sheet1.write(row, col, rowTxt)
    #
    #     col += 1 #进入下一列
    #
    #     if (col > colLen - 1):
    #         col = 1
    #         row += 1 #换行
    #
    workbook.save('test2.xls')

def inserDb(bug):
    bug.save()

if __name__ == "__main__":
    # 从返回结果来看，有登录成功
    loginOrviboWiki("wangchuanjin", "orvibo888")
    # read_excel()
